package com.hnkywl.sts.action.htdygl;

import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.entity.htgl.*;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.service.htdygl.DynaFormService;
import com.hnkywl.sts.service.htdygl.HtdyService;
import com.hnkywl.sts.service.htdygl.HtwbService;
import com.hnkywl.sts.service.htgl.BghtService;
import com.hnkywl.sts.service.htgl.CghtService;
import com.hnkywl.sts.service.htgl.HtService;
import com.hnkywl.sts.service.htgl.XshtService;
import com.hnkywl.sts.util.Constant;
import com.hnkywl.sts.util.StringFormat;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-4-17
 * Time:  上午 11:28
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/htdygl/htwb")
public class HtwbAction extends SimpleActionSupport {

    // 合同文本service
    private HtwbService htwbService;

    // 动态页面service
    private DynaFormService dynaFormService;

    // 销售合同service
    private XshtService xshtService;

    // 采购合同
    private CghtService cghtService;

    //保供合同service
    private BghtService bghtService;

    // 合同定义service
    private HtdyService htdyService;

    private HtService htService;

    // 合同文本实体
    private Htwb htwb;

    // 合同id
    private String htId;

    // 合同定义id
    private String htdyId;

    // 合同模板
    private String htmbId;

    // 合同文本id
    private String htwbId;

    //合同内容以及值
    private String htContent;

    // 合同类型
    private String htType;

    private GsjgDao gsjgDao;

    private static final String UNIT = "万千佰拾亿千佰拾万千佰拾元角分";

    private static final String DIGIT = "零壹贰叁肆伍陆柒捌玖";

    private static final double MAX_VALUE = 9999999999999.99D;

    public static String changeUppercase(double v) {
        if (v < 0 || v > MAX_VALUE)
            return "参数非法!";
        long l = Math.round(v * 100);
        if (l == 0)
            return "零元整";
        String strValue = l + "";
        // i用来控制数
        int i = 0;
        // j用来控制单位
        int j = UNIT.length() - strValue.length();
        String rs = "";
        boolean isZero = false;
        for (; i < strValue.length(); i++, j++) {
            char ch = strValue.charAt(i);

            if (ch == '0') {
                isZero = true;
                if (UNIT.charAt(j) == '亿' || UNIT.charAt(j) == '万' || UNIT.charAt(j) == '元') {
                    rs = rs + UNIT.charAt(j);
                    isZero = false;
                }
            } else {
                if (isZero) {
                    rs = rs + "零";
                    isZero = false;
                }
                rs = rs + DIGIT.charAt(ch - '0') + UNIT.charAt(j);
            }
        }

        if (!rs.endsWith("分")) {
            rs = rs + "整";
        }
        rs = rs.replaceAll("亿万", "亿");
        return rs;
    }

    @Action("htwbDetail")
    public void htwb() {
        //取得关联合同
        Ht ht = this.htService.findHt(Long.valueOf(htId));
        //取得合同定义
        Htdy htdy = this.htdyService.findHtdyById(htdyId);
        if (ht == null) {
            this.renderHtml("没有找到关联的合同，请联系管理员！");
            return;
        }

        if (htdy == null) {
            this.renderHtml("没有找到相对应的合同定义，请联系管理员！");
            return;
        }

        try {
            this.renderHtml(dealHtml(getHtml(htdy, ht.getHtwb()), htdy, ht));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchMethodException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    // 保存合同文本以及内容
    @Action("saveHtwb")
    public void saveHtwb() {
        if (StringUtils.isNotEmpty(htdyId) && StringUtils.isNotEmpty(htContent)) {
            Map<String, String> formDataMap = new HashMap<String, String>();
            String[] formData = getHtContent().split(",o");
            for (int i = 0; i < formData.length; i++) {
                String[] key_value = formData[i].split(":o", 2);
                formDataMap.put(key_value[0], key_value[1]);
            }
            try {
                this.dynaFormService.saveFormData(formDataMap, htId, htwbId, htdyId);
                renderJson("{\"statusCode\":\"200\", \"message\":\"" + "保存合同文本以及内容成功！" + "\"}");
            } catch (Exception e) {
                renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
            }
        }
    }

    /**
     * 取合同html
     *
     * @param htdy
     * @return
     */
    private String getHtml(Htdy htdy, Htwb htwb) {
        if (htwb == null) {
            //TODO
            return dynaFormService.getFormHtml(htdy, htmbId);
        } else {
            return dynaFormService.getFormHtml(htwb);
        }
    }

    /**
     * 处理合同html，绑定值
     *
     * @param html
     * @param htdy
     * @param ht
     * @return
     */
    private String dealHtml(String html, Htdy htdy, Ht ht) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Document document = Jsoup.parse(html);
        // 已经有合同文本
        for (Htys htys : htdy.getHtysList()) {
            // 新增合同时,通过反射来取值
            if (null == ht.getHtwb()) {
                if (null != htys.getMrz()) {
                    Elements elements = document.select("[name=" + htys.getYsid() + "]");
                    //判断
                    if (Pattern.compile("^\\[.+\\]$").matcher(htys.getMrz()).find()) {
                        elements.val(getValue(ht.getHzf(), htys.getMrz()));
                        continue;
                    }
                    ;

                    Class htclass = Class.forName("com.hnkywl.sts.entity.htgl.Ht");
                    Field[] fields = htclass.getDeclaredFields();
                    for (Field field : fields) {
                        String firstLetter = field.getName().substring(0, 1).toUpperCase();
                        String getter = "get" + firstLetter + field.getName().substring(1);
                        if (htys.getMrz().equals(getter)) {
                            Method method = ht.getClass().getMethod(getter, new Class[]{});
                            Object value = method.invoke(ht, new Object[]{});

                            if (null != value) {
                                if (value instanceof Gsjg) {
                                    elements.val(((Gsjg) value).getQc());
                                } else {
                                    // 判断是否是时间
                                    if (field.getGenericType().toString().equals("class java.util.Date")) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        elements.val(sdf.format(value));
                                    } else {
                                        elements.val(value.toString());
                                    }
                                }
                            } else {
                                elements.val("");
                            }

                        }

                    }
                }
            }
            // 表格
            if (null != htys.getYxlx()) {
                if (htys.getYxlx() == Constant.XXLX_TABLE) {
                    String dtailTable = getTable(ht.getHtmxList());

                    document.select("[name=" + htys.getYsid() + "]").attr("type", "hidden").after(dtailTable);
                }
            }
        }
        return document.toString();
    }

    private String getValue(Gsjg gsjg, String key) {
        if ("[dwdz]".equals(key)) {
            return getDwdz(gsjg);
        } else if ("[fddlr]".equals(key)) {
            return getFddlr(gsjg);
        } else if ("[wtdlr]".equals(key)) {
            return getWtdlr(gsjg);
        } else if ("[cz]".equals(key)) {
            return getCz(gsjg);
        } else if ("[dh]".equals(key)) {
            return getDh(gsjg);
        } else if ("[khyh]".equals(key)) {
            return getKhyh(gsjg);
        } else if ("[zh]".equals(key)) {
            return getZh(gsjg);
        } else if ("[yzbm]".equals(key)) {
            return getYzbm(gsjg);
        } else if ("[nsh]".equals(key)) {
            return getNsh(gsjg);
        } else {
            return "";
        }
    }

    private String getDwdz(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getBgdz() == null) {
            return "";
        }

        return gsjg.getQyfr().getBgdz();
    }

    private String getFddlr(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getFddlr() == null) {
            return "";
        }

        return gsjg.getQyfr().getFddlr();
    }

    private String getWtdlr(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getFddlr() == null) {
            return "";
        }

        return gsjg.getQyfr().getFddlr();
    }

    private String getCz(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getCz() == null) {
            return "";
        }

        return gsjg.getQyfr().getCz();
    }

    private String getDh(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getDh() == null) {
            return "";
        }

        return gsjg.getQyfr().getDh();
    }

    private String getKhyh(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getKhh() == null) {
            return "";
        }

        return gsjg.getQyfr().getKhh();
    }

    private String getZh(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getZh() == null) {
            return "";
        }

        return gsjg.getQyfr().getZh();
    }

    private String getYzbm(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getYzbm() == null) {
            return "";
        }

        return gsjg.getQyfr().getYzbm();
    }

    private String getNsh(Gsjg gsjg) {
        if (gsjg.getQyfr() == null) {
            return "";
        }

        if (gsjg.getQyfr().getNsh() == null) {
            return "";
        }

        return gsjg.getQyfr().getNsh();
    }

    /**
     * 拼接table
     *
     * @param htmxes
     * @return
     */
    private String getTable(List<Htmx> htmxes) {
        // 取得合同明细
        StringBuffer sbTable = new StringBuffer();
        DecimalFormat df = new DecimalFormat("#0.0000");
        Double hsjezh = 0d;
        if (null != htmxes) {
            sbTable.append("<table class=\"tb intb\" style=\"width: 100%;\"><thead>");
            sbTable.append("<tr>");
            sbTable.append("<td>销售系统子项号</td><td>物资编码</td><td>品名</td><td>规格型号</td><td>材质</td><td>产地</td>" +
                    "<td>数量</td><td>记重方式</td><td>含税单价</td><td>不含税单价</td>" +
                    "<td>含税总金额</td><td>备注</td>");
            sbTable.append("</tr></thead><tbody>");
            String trTemplate = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td>{8}</td><td>{9}</td><td>{10}</td><td>{11}</td></tr>";
            for (int i = 0; i < htmxes.size(); i++) {
                String xsxt_xsdh="", code = "", name = "", ggxh = "",cz = "", cd = "", sbsl = "", jzfs = "", hsj = "", bhsj = "", hsje = "", bz = "";
                if (htmxes.get(i).getWzgg() != null) {
                    code = htmxes.get(i).getWzgg().getCode() == null ? "" : htmxes.get(i).getWzgg().getCode();
                    name = htmxes.get(i).getWzgg().getName() == null ? "" : htmxes.get(i).getWzgg().getName();
                    ggxh = htmxes.get(i).getWzgg().getGgxh() == null ? "" : htmxes.get(i).getWzgg().getGgxh();
                    cz = htmxes.get(i).getWzgg().getCz()==null?"":htmxes.get(i).getWzgg().getCz();

                    //判断是否保供合同
                    if (htmxes.get(i).getHt() instanceof Cght) {
                        Cght cght = (Cght) htmxes.get(i).getHt();
                        if (cght.getCglx().equals("bght")) {
                            code = htmxes.get(i).getWzgg().getOldcode() == null ? "" : htmxes.get(i).getWzgg().getOldcode();
                        }
                    }
                }

                if (htmxes.get(i).getXsxt_xsdh() != null) {
                    xsxt_xsdh = htmxes.get(i).getXsxt_xsdh().toString();
                }
                if (htmxes.get(i).getCd() != null) {
                    cd = htmxes.get(i).getCd().getZ();
                }

                if (htmxes.get(i).getSbsl() != null) {
                    sbsl = htmxes.get(i).getSbsl().toString();
                }

                if (htmxes.get(i).getJzfs() != null) {
                    jzfs = htmxes.get(i).getJzfs().getZ();
                }

                if (htmxes.get(i).getHsj() != null) {
                    hsj = htmxes.get(i).getHsj().toString();
                }

                if (htmxes.get(i).getBhsj() != null) {
                    bhsj = htmxes.get(i).getBhsj().toString();
                }

                if (htmxes.get(i).getHsje() != null) {
                    hsje = df.format(htmxes.get(i).getHsje());
                    Double mhsje = (Double) htmxes.get(i).getHsje();
                    BigDecimal bhsje = new BigDecimal(mhsje);
                    Double dhsje = bhsje.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    hsjezh += dhsje;
                }

                if (htmxes.get(i).getBz() != null) {
                    bz = htmxes.get(i).getBz();
                }

                String trData = StringFormat.format(trTemplate,
                        xsxt_xsdh,code, name, ggxh,cz, cd, sbsl, jzfs,hsj, bhsj, hsje, bz);
                sbTable.append(trData);
            }
            String shsje = df.format(hsjezh);
            String trFooter = StringFormat.format("<tr><td>{0}</td><td colspan='9'>{2}</td><td>{3}</td><td></tr>", "合计：",
                    "合计：", changeUppercase(Double.parseDouble(shsje)), shsje);
            sbTable.append(trFooter);
        }
        sbTable.append("</tbody></table>");
        return sbTable.toString();
    }


    @Autowired
    public void setHtwbService(HtwbService htwbService) {
        this.htwbService = htwbService;
    }

    @Autowired
    public void setDynaFormService(DynaFormService dynaFormService) {
        this.dynaFormService = dynaFormService;
    }

    @Autowired
    public void setXshtService(XshtService xshtService) {
        this.xshtService = xshtService;
    }

    @Autowired
    public void setHtdyService(HtdyService htdyService) {
        this.htdyService = htdyService;
    }


    @Autowired
    public void setCghtService(CghtService cghtService) {
        this.cghtService = cghtService;
    }

    public Htwb getHtwb() {
        return htwb;
    }

    public void setHtwb(Htwb htwb) {
        this.htwb = htwb;
    }

    public String getHtId() {
        return htId;
    }

    public void setHtId(String htId) {
        this.htId = htId;
    }

    public String getHtdyId() {
        return htdyId;
    }

    public void setHtdyId(String htdyId) {
        this.htdyId = htdyId;
    }

    public String getHtContent() {
        return htContent;
    }

    public void setHtContent(String htContent) {
        this.htContent = htContent;
    }

    public String getHtwbId() {
        return htwbId;
    }

    public void setHtwbId(String htwbId) {
        this.htwbId = htwbId;
    }

    public String getHtType() {
        return htType;
    }

    public void setHtType(String htType) {
        this.htType = htType;
    }

    public String getHtmbId() {
        return htmbId;
    }

    public void setHtmbId(String htmbId) {
        this.htmbId = htmbId;
    }

    @Autowired
    public void setHtService(HtService htService) {
        this.htService = htService;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
}
